<?php
header('Content-Type: application/json');
require_once '../config/db_config.php';

// 获取数据库连接
$conn = getDBConnection();

// 处理不同的HTTP请求方法
$method = $_SERVER['REQUEST_METHOD'];

switch($method) {
    case 'GET':
        // 获取地点列表或单个地点详情
        if (isset($_GET['id'])) {
            getPlace($conn, $_GET['id']);
        } else {
            getPlaces($conn);
        }
        break;
        
    case 'POST':
        // 添加新地点
        $data = json_decode(file_get_contents('php://input'), true);
        addPlace($conn, $data);
        break;
        
    case 'PUT':
        // 更新地点信息
        $data = json_decode(file_get_contents('php://input'), true);
        if (isset($_GET['id'])) {
            updatePlace($conn, $_GET['id'], $data);
        }
        break;
        
    case 'DELETE':
        // 删除地点
        if (isset($_GET['id'])) {
            deletePlace($conn, $_GET['id']);
        }
        break;
}

// 获取所有地点
function getPlaces($conn) {
    try {
        $stmt = $conn->query("SELECT * FROM places");
        $places = $stmt->fetchAll(PDO::FETCH_ASSOC);
        
        // 获取每个地点的属性
        foreach ($places as &$place) {
            $stmt = $conn->prepare("SELECT attribute_name, attribute_value FROM place_attributes WHERE place_id = ?");
            $stmt->execute([$place['id']]);
            $place['attributes'] = $stmt->fetchAll(PDO::FETCH_ASSOC);
        }
        
        echo json_encode(['status' => 'success', 'data' => $places]);
    } catch(PDOException $e) {
        http_response_code(500);
        echo json_encode(['status' => 'error', 'message' => $e->getMessage()]);
    }
}

// 获取单个地点详情
function getPlace($conn, $id) {
    try {
        $stmt = $conn->prepare("SELECT * FROM places WHERE id = ?");
        $stmt->execute([$id]);
        $place = $stmt->fetch(PDO::FETCH_ASSOC);
        
        if ($place) {
            // 获取地点属性
            $stmt = $conn->prepare("SELECT attribute_name, attribute_value FROM place_attributes WHERE place_id = ?");
            $stmt->execute([$id]);
            $place['attributes'] = $stmt->fetchAll(PDO::FETCH_ASSOC);
            
            echo json_encode(['status' => 'success', 'data' => $place]);
        } else {
            http_response_code(404);
            echo json_encode(['status' => 'error', 'message' => '地点不存在']);
        }
    } catch(PDOException $e) {
        http_response_code(500);
        echo json_encode(['status' => 'error', 'message' => $e->getMessage()]);
    }
}

// 添加新地点
function addPlace($conn, $data) {
    try {
        $conn->beginTransaction();
        
        // 插入地点基本信息
        $stmt = $conn->prepare("INSERT INTO places (name, latitude, longitude, category, description, history, image_url) 
                               VALUES (?, ?, ?, ?, ?, ?, ?)");
        $stmt->execute([
            $data['name'],
            $data['latitude'],
            $data['longitude'],
            $data['category'],
            $data['description'] ?? null,
            $data['history'] ?? null,
            $data['image_url'] ?? null
        ]);
        
        $placeId = $conn->lastInsertId();
        
        // 插入地点属性
        if (isset($data['attributes']) && is_array($data['attributes'])) {
            $stmt = $conn->prepare("INSERT INTO place_attributes (place_id, attribute_name, attribute_value) VALUES (?, ?, ?)");
            foreach ($data['attributes'] as $attr) {
                $stmt->execute([$placeId, $attr['name'], $attr['value']]);
            }
        }
        
        $conn->commit();
        echo json_encode(['status' => 'success', 'message' => '地点添加成功', 'id' => $placeId]);
    } catch(PDOException $e) {
        $conn->rollBack();
        http_response_code(500);
        echo json_encode(['status' => 'error', 'message' => $e->getMessage()]);
    }
}

// 更新地点信息
function updatePlace($conn, $id, $data) {
    try {
        $conn->beginTransaction();
        
        // 更新地点基本信息
        $stmt = $conn->prepare("UPDATE places SET 
                               name = ?, 
                               latitude = ?, 
                               longitude = ?, 
                               category = ?, 
                               description = ?, 
                               history = ?, 
                               image_url = ? 
                               WHERE id = ?");
        $stmt->execute([
            $data['name'],
            $data['latitude'],
            $data['longitude'],
            $data['category'],
            $data['description'] ?? null,
            $data['history'] ?? null,
            $data['image_url'] ?? null,
            $id
        ]);
        
        // 更新地点属性
        if (isset($data['attributes']) && is_array($data['attributes'])) {
            // 删除旧属性
            $stmt = $conn->prepare("DELETE FROM place_attributes WHERE place_id = ?");
            $stmt->execute([$id]);
            
            // 插入新属性
            $stmt = $conn->prepare("INSERT INTO place_attributes (place_id, attribute_name, attribute_value) VALUES (?, ?, ?)");
            foreach ($data['attributes'] as $attr) {
                $stmt->execute([$id, $attr['name'], $attr['value']]);
            }
        }
        
        $conn->commit();
        echo json_encode(['status' => 'success', 'message' => '地点更新成功']);
    } catch(PDOException $e) {
        $conn->rollBack();
        http_response_code(500);
        echo json_encode(['status' => 'error', 'message' => $e->getMessage()]);
    }
}

// 删除地点
function deletePlace($conn, $id) {
    try {
        $stmt = $conn->prepare("DELETE FROM places WHERE id = ?");
        $stmt->execute([$id]);
        
        if ($stmt->rowCount() > 0) {
            echo json_encode(['status' => 'success', 'message' => '地点删除成功']);
        } else {
            http_response_code(404);
            echo json_encode(['status' => 'error', 'message' => '地点不存在']);
        }
    } catch(PDOException $e) {
        http_response_code(500);
        echo json_encode(['status' => 'error', 'message' => $e->getMessage()]);
    }
}
?> 